package com.woniuxy.shiro.utils;

import org.apache.shiro.mgt.SessionStorageEvaluator;
import org.apache.shiro.spring.LifecycleBeanPostProcessor;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.mgt.DefaultWebSessionStorageEvaluator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Filter;
import java.util.HashMap;
import java.util.Map;

/**
 * @author: mayuhang  <br/>
 * Date: 2021/4/23:0:35  <br/>
 * Description: shiro核心配置, 中央大脑 SecurityManager 相关配置 等同于之前玩 shiro-realm.ini的时候
 */
@Configuration
public class ShiroConfig {

    //配置安全管理器, 传入自己写的自定义域  传入的参数是我们自定义的域
    @Bean
    public DefaultWebSecurityManager securityManager(MyRealm realm) {
        //使用默认的web安全管理器
        DefaultWebSecurityManager securityManager = new
                DefaultWebSecurityManager(realm);
        //将自定义的realm交给安全管理器统一调度管理
        securityManager.setRealm(realm);
        return securityManager;
    }
    //Filter工厂，设置对应的过滤条件和跳转条件, 这个地方 需要配置 过滤 所有请求
    //类似之前 DispatchServlet 中配置的 /
    @Bean("shiroFilterFactoryBean")
    public ShiroFilterFactoryBean getFilterFactoryBean(DefaultWebSecurityManager manager){
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        //在这个filter工厂里面, 放入我们刚创建的SecurityManager
        shiroFilterFactoryBean.setSecurityManager(manager);
        //JWTFilter把他配置进来!
        HashMap<String, Filter> filterMap = new HashMap<>();
        filterMap.put("JWT",new JWTFilter());
        shiroFilterFactoryBean.setFilters(filterMap);

        //配置url请求过滤条件!
        //过滤 URL请求, 使用 anon 任何人都能访问
        /*
        *   url过滤 条件 简写
        *   anon  匿名  所有用户未登录时 都能访问的接口
        *   authc  需要登录认证后 才能访问
        */

        HashMap<String, String> objectObjectHashMap = new HashMap<>();
        objectObjectHashMap.put("/login","anon");
        //这个地方  就是所有url请求都需要经过JWTFilter过滤器处理
        objectObjectHashMap.put("/**","JWT");
        //把过滤条件 配置到过滤器bean中
        shiroFilterFactoryBean.setFilterChainDefinitionMap(objectObjectHashMap);
        return shiroFilterFactoryBean;
    }
    //开启shiro注解支持
    @Bean
    public AuthorizationAttributeSourceAdvisor
    authorizationAttributeSourceAdvisor(DefaultWebSecurityManager securityManager) {
        AuthorizationAttributeSourceAdvisor advisor = new
                AuthorizationAttributeSourceAdvisor();
        advisor.setSecurityManager(securityManager);
        return advisor;
    }
}
